<template>
  <div class="form">
    <div class="title">注册复试导演账号</div>
    <div class="group">
      <input type="text" placeholder="请输入真实姓名" v-model="state.name" />
    </div>
    <div class="group">
      <input type="tel" placeholder="请输入手机号码" v-model="state.mobile" />
    </div>
    <div class="group">
      <input
        type="password"
        placeholder="请输入登陆密码"
        v-model="state.password"
      />
    </div>
    <div class="group">
      <input type="number" placeholder="验证码" v-model="state.code" />
      <button class="sendmsg" @click="sendMsg" :disabled="msgSended">
        {{ sendText }}
      </button>
    </div>
    <button class="submit" @click="submit">注册</button>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import ajax from "../../util/http";
import { reactive, ref, getCurrentInstance } from "vue";
import form from "../../util/validator";
const { proxy } = getCurrentInstance();

const router = useRouter();
const route = useRoute();

const count = ref(60);
const sendText = ref("获取");
const msgSended = ref(false);
const state = reactive({
  name: "",
  mobile: "",
  password: "",
  code: "",
});

const submit = () => {
  let data = {
    cid: route.query.cid,
    mobile: state.mobile,
    name: state.name,
    password: state.password,
    code: state.code,
  };
  let rules = [
    {
      name: "name",
      rule: ["required"],
      msg: ["请输入真实姓名"],
    },
    {
      name: "mobile",
      rule: ["required", "isMobile"],
      msg: ["请输入手机号", "请输入正确的手机号"],
    },
    {
      name: "password",
      rule: ["required"],
      msg: ["请输入登陆密码"],
    },
    {
      name: "code",
      rule: ["required"],
      msg: ["请输入验证码"],
    },
  ];
  let checkForm = form.validation(data, rules);
  if (!checkForm) {
    ajax.post("/star/oper/register", data).then((res) => {
      if (res.code == 1) {
        // proxy.$message({ content: res.msg });
        router.push({
          path: "/login",
          query: {
            role: "second",
            cid: route.query.cid,
          },
        });
      }
    });
  } else {
    proxy.$message({ content: checkForm });
  }
};

const countdown = () => {
  if (count.value > 0) {
    msgSended.value = true;
    sendText.value = count.value + "秒后重试";
    count.value--;
    setTimeout(() => {
      countdown();
    }, 1000);
  } else {
    count.value = 60;
    sendText.value = "获取";
    msgSended.value = false;
  }
};

const sendMsg = () => {
  let rules = [
    {
      name: "mobile",
      rule: ["required", "isMobile"],
      msg: ["请输入手机号", "请输入正确的手机号"],
    },
  ];
  let checkForm = form.validation({ mobile: state.mobile }, rules);
  if (!checkForm) {
    ajax
      .post("/sms/send", {
        mobile: state.mobile,
        event: "mobilelogin",
      })
      .then((res) => {
        if (res.code == 1) {
          countdown();
        }
      });
  } else {
    proxy.$message({ content: checkForm });
  }
};
</script>